package com.ddf.pluto.controller;

import com.ddf.pluto.utils.UploadImg;
import com.ddf.publics.config.Utill;
import com.ddf.publics.entity.*;
import com.ddf.publics.service.*;
import com.ddf.publics.tool.Constant;
import com.ddf.publics.utils.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.security.Principal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @program: dingding-financial
 * @description: 借款前端控制层
 * @author: Mr.pluto
 * @create: 2020-06-10 08:27
 **/
@Controller
@RequestMapping("/loan")
public class    LoanController {

    /**
     * 借款标类型跟借款标
     */
    @Resource
    private DebitTypeService debitTypeService;
    @Resource
    private LoanApplicationService loanApplicationService;
    @Resource
    private UserInfoService userInfoService;
    @Autowired
    private LoginService service;
    @Resource
    private GuarantyStyleService guarantyStyleService;
    @Resource
    private ClanTabService clanTabService;
    @Autowired
    private RedisUtil redisUtil;
    @Resource
    private LoginService loginService;

    @Value("${server.port}")
    private String port;

    /**
     * 借贷主页
     * @param model
     * @param principal
     * @return
     */
    @RequestMapping("/main")
    public String toLoanPage(Model model,Principal principal){
        List<DebitType> list = debitTypeService.queryAllList();
        User user = service.queryByPhone(principal.getName());
//        boolean tempFlag = userInfoService.judgeUserInfo(user.getId());
//        if (!tempFlag)
//            return "forward:userSet";
        int orderCount = loanApplicationService.queryOrderById(user.getId());
        String flag = "0";
        if(orderCount>0){
            flag = "1";
        }
        UserInfo userInfo = new UserInfo();
        userInfo.setUId(user.getId());
        List<UserInfo> list1 = userInfoService.queryUserByObj(userInfo);
        if(list1.size()!=0){
            userInfo = list1.get(0);
        }
        model.addAttribute("flag",flag);
        model.addAttribute("deb",list);
        model.addAttribute("user",userInfo);
        return "loan/myjk";
    }

    /**
     * 装载信用借贷信息
     * @param loanApplication
     * @param model
     * @param principal
     * @return
     */
    @RequestMapping("/affirmInfo")
    public String affirmInfo(LoanApplication loanApplication, Model model, Principal principal, HttpServletRequest request){
        //获取session里的对象
        User user = service.queryByPhone(principal.getName());
        UserInfo userInfo = this.getUserInfo(user.getId());
        if(userInfo==null){
            return "";
        }
        //将紧急联系人存入redis
        List<ClanTab> clist = this.insertClan(request);
        redisUtil.set("clan:"+user.getId(),clist,60*60*24);

        //获取借贷类型利率
        DebitType debitType = debitTypeService.queryById(loanApplication.getLoanType());
        //将信息填入loanapplication
        loanApplication.setUserInfo(user,userInfo);
        model.addAttribute("clan",clist);
        model.addAttribute("user",userInfo);
        model.addAttribute("loan",loanApplication);
        model.addAttribute("debit",debitType);
        return "loan/loan_info";
    }

    /**
     * 装载抵押借贷信息
     * @param files
     * @param loanApplication
     * @param principal
     * @param guarantyStyle
     * @return
     */
    @RequestMapping("/addMortgage")
    public String addMortgage(MultipartFile files, MultipartFile scoreImg, LoanApplication loanApplication,
                              Principal principal, GuarantyStyle guarantyStyle,Model model,HttpServletRequest request){
        User user = service.queryByPhone(principal.getName());

        Map map = null;
        //储存图片
        if(files==null&&scoreImg!=null){
            map = UploadImg.addImg(scoreImg, Constant.PLEDGE_IMG_PATH,"weilidai");
        }else if(scoreImg==null&&files!=null){
            map = UploadImg.addImg(files, Constant.PLEDGE_IMG_PATH,"pledgeimg");
        }
        guarantyStyle.setImg(map.get("newname").toString());
//        担保方式
//        guarantyStyle = guarantyStyleService.insert(guarantyStyle);
        redisUtil.set("guarantyStyle:"+user.getId(),guarantyStyle);
        //获取借贷类型利率
        DebitType debitType = debitTypeService.queryById(loanApplication.getLoanType());
        loanApplication.setOrderTime(new Date());
        loanApplication.setInterestRate(debitType.getYearInterset());
        loanApplication.setGuarantyStyle(guarantyStyle.getId());

        UserInfo userInfo = this.getUserInfo(user.getId());
//        if(userInfo==null){
//            return "redirect:userSet";
//        }
        //将紧急联系人存入redis
        List<ClanTab> clist = this.insertClan(request);
        redisUtil.set("clan:"+user.getId(),clist,60*60*24);

        loanApplication.setUserInfo(user,userInfo);
//        给审核备注附初始值
        loanApplication.setAuditComment(" ");
        model.addAttribute("clan",clist);
        model.addAttribute("loan",loanApplication);
        model.addAttribute("user",userInfo);
        model.addAttribute("gua",guarantyStyle);
        model.addAttribute("debit",debitType);
        return "loan/pledgeLoanInfo";
    }

    /**
     * 新增信用贷订单
     * @param loanApplication
     * @param model
     * @param principal
     * @return
     */
    @RequestMapping("/addOrder")
    public String addOrder(LoanApplication loanApplication,Model model,Principal principal,HttpServletRequest request){
        User user = service.queryByPhone(principal.getName());
        //获取借贷类型利率
        DebitType debitType = debitTypeService.queryById(loanApplication.getLoanType());
        loanApplication.setInterestRate(debitType.getYearInterset());
        loanApplication.setAuditComment(" ");
        //判断是否不是信用贷，取出抵押信息存进订单表
        if(loanApplication.getLoanType()!=Constant.LOAN_TYPE_XINYONG){
            GuarantyStyle guarantyStyle;
            guarantyStyle = (GuarantyStyle) redisUtil.get("guarantyStyle:"+user.getId());
            guarantyStyle = guarantyStyleService.insert(guarantyStyle);
            loanApplication.setGuarantyStyle(guarantyStyle.getId());
        }
        //将紧急联系人存入redis
        List<ClanTab> list = (List) redisUtil.get("clan:"+user.getId());
        redisUtil.del("clan:"+user.getId());
        loanApplication.setOrderTime(new Date());
        loanApplication = loanApplicationService.insert(loanApplication);
        LoanApplication finalLoanApplication = loanApplication;
        list.forEach(c->{
            ClanTab temp = c;
            temp.setLId(finalLoanApplication.getLId());
            clanTabService.insert(temp);
        });

        String url=request.getScheme()+"://"+ request.getServerName()+":"+port;//+request.getRequestURI();
//        System.out.println("协议名：//域名="+url2);

        return "redirect:"+url+"/loanHistory";
    }

    //抵押贷、微粒贷取消
    @RequestMapping("/deleteguarantyStyle")
    @ResponseBody
    public void deleteguarantyStyle(GuarantyStyle guarantyStyle,Principal principal){
        File file = new File(Constant.PLEDGE_IMG_PATH+"\\"+guarantyStyle.getImg());
        User user = service.queryByPhone(principal.getName());
        redisUtil.del("guarantyStyle:"+user.getId());
        redisUtil.del("clan:"+user.getId());
        file.delete();
    }
    //信用贷取消
    @RequestMapping("/deleteClan")
    @ResponseBody
    public void deleteClan(Principal principal){
        User user = service.queryByPhone(principal.getName());
        redisUtil.del("clan:"+user.getId());
    }

    /**
     * 根据用户id获取用户详细信息
     * @param id
     * @return
     */
    public UserInfo getUserInfo(int id){
        UserInfo userInfo= new UserInfo();
        userInfo.setUId(id);
        List<UserInfo> list = userInfoService.queryUserByObj(userInfo);
        if (list==null)
            return null;
        userInfo = list.get(0);
        return userInfo;
    }

    @RequestMapping("/judgePwd")
    @ResponseBody
    public String judgePassword(String paypwd,Principal principal){
        User user = loginService.queryByPhone(principal.getName());
        int userId = user.getId();
        UserInfo userInfo=userInfoService.userInfoList(userId);
        //密码输入5次以上错误不能支付
        Integer paynum = (Integer) redisUtil.get("pay:" + userId);
        if(paynum!=null&&paynum>=5){
            return "2";
        }
        //密码错误
        if(!userInfo.getPayPwd().equals(paypwd)){
            redisUtil.incr("pay:"+userId,1, Utill.TodaySeconds());
            return "1";
        }
        //密码正确清除密码错误记录
        redisUtil.del("pay:"+userId);
        return "0";
    }

    @RequestMapping("/judgeUser")
    @ResponseBody
    public String judgeUser(Principal principal){
        User user = service.queryByPhone(principal.getName());
        String flag = "1";
        UserInfo userInfo = new UserInfo();
        userInfo.setUId(user.getId());
        List<UserInfo> list = userInfoService.queryUserByObj(userInfo);
        if(list.size()!=0){
            userInfo = list.get(0);
        }
        if(list.size()==0){
             flag="0";
        }else if("".equals(userInfo.getIdCard()) || userInfo.getIdCard()==null){
            flag="0";
        }else if("".equals(userInfo.getPayPwd()) || userInfo.getPayPwd()==null){
            flag="0";
            }else if("".equals(userInfo.getRealName()) || userInfo.getRealName()==null){
            flag="0";
        }
        return flag;
    }

    @RequestMapping("/test")
    public String totest(HttpServletRequest request){
//        System.out.println(request.getRequestURI());
//        System.out.println(request.getContextPath());
//        System.out.println(request.getHttpServletMapping());
//        System.out.println(request.getServletPath());

//        ActionContext ctx = ActionContext.getContext();
//        HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
//        HttpServletResponse response = (HttpServletResponse)ctx.get(ServletActionContext.HTTP_RESPONSE);

        String url = request.getScheme()+"://"+ request.getServerName()+request.getRequestURI()+"?"+request.getQueryString();
        System.out.println("获取全路径（协议类型：//域名/项目名/命名空间/action名称?其他参数）url="+url);
        String url2=request.getScheme()+"://"+ request.getServerName();//+request.getRequestURI();
        System.out.println("协议名：//域名="+url2);



        System.out.println("获取项目名="+request.getContextPath());
        System.out.println("获取参数="+request.getQueryString());
        System.out.println("获取全路径="+request.getRequestURL());

        return "loan/test2";
    }

//    @RequestMapping("/test")
//    public String totest(){
//        return "loan/test2";
//    }

    public List<ClanTab> insertClan(HttpServletRequest request){
        List<ClanTab> list = new ArrayList();
        String[] clanName = request.getParameterValues("clan_name");
        String[] clanRelation = request.getParameterValues("clan_relation");
        String[] clanPhone = request.getParameterValues("clan_phone");
        for (int i = 0; i <2; i++) {
            ClanTab clanTab = new ClanTab();
            clanTab.setCName(clanName[i]);
            clanTab.setCPhone(clanPhone[i]);
            clanTab.setCRelation(clanRelation[i]);
//            clanTab.setLId(lid);
            list.add(clanTab);
        }
        return list;
    }

}
